package cn.ai.shoes.core.config;


import cn.ai.shoes.common.exception.ServiceException;
import cn.ai.shoes.core.mapper.UserMapper;
import cn.ai.shoes.core.service.UserService;
import cn.ai.shoes.core.utils.AuthenticationUtils;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.Primary;

@Primary
@Component
public class DBUserDetailsManager implements UserDetailsManager, UserDetailsPasswordService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private UserService userService;

    public DBUserDetailsManager() {
        System.out.println("DBUserDetailsManager 被创建");
    }

    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        return null;
    }

    @Override
    public void createUser(UserDetails userDetails) {
    }

    @Override
    public void updateUser(UserDetails user) {

    }

    @Override
    public void deleteUser(String username) {

    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {

    }

    @Override
    public boolean userExists(String username) {
        return false;
    }
    /**
     * 从数据库中查询用户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("调用了loadUserByUsername: " + username);
        try {
            UserDetails ud = AuthenticationUtils.createUserDetails(username, null, userService);
            System.out.println("查到的密码: " + ud.getPassword());
            return ud;
        } catch (ServiceException e) {
            throw new UsernameNotFoundException("用户不存在", e);
        }
    }

}
